// -*- coding: utf-8 -*-
/*
author: zengbin93
email: zeng_bin8888@163.com
create_dt: 2022/12/16 19:37
describe: SVC模块工具功能
*/

use crate::svc::base::{DataFrame, StyleConfig};
use serde_json::Value;
use std::collections::HashMap;

/// 显示代码编辑器
pub fn show_code_editor(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("代码", crate::svc::base::DataType::String, false);
    result.add_column("语言", crate::svc::base::DataType::String, false);
    result.add_column("主题", crate::svc::base::DataType::String, false);
    
    result
}

/// 格式化代码
pub fn format_code(code: &str, language: &str) -> String {
    // 这里是一个简化的代码格式化实现
    // 实际应用中可能需要更复杂的格式化逻辑
    match language {
        "python" => format_python_code(code),
        "rust" => format_rust_code(code),
        "javascript" => format_javascript_code(code),
        _ => code.to_string(),
    }
}

/// 格式化Python代码
fn format_python_code(code: &str) -> String {
    // 简化的Python代码格式化
    let mut formatted = String::new();
    let mut indent_level = 0;
    
    for line in code.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            formatted.push('\n');
            continue;
        }
        
        // 处理缩进
        if trimmed.starts_with("if ") || trimmed.starts_with("for ") || 
           trimmed.starts_with("while ") || trimmed.starts_with("def ") ||
           trimmed.starts_with("class ") || trimmed.starts_with("try:") ||
           trimmed.starts_with("except") || trimmed.starts_with("finally:") ||
           trimmed.starts_with("with ") {
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
            indent_level += 1;
        } else if trimmed.starts_with("return ") || trimmed.starts_with("break") ||
                  trimmed.starts_with("continue") || trimmed.starts_with("pass") {
            indent_level = indent_level.saturating_sub(1);
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
        } else if trimmed == "else:" || trimmed == "elif " {
            indent_level = indent_level.saturating_sub(1);
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
            indent_level += 1;
        } else {
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
        }
    }
    
    formatted
}

/// 格式化Rust代码
fn format_rust_code(code: &str) -> String {
    // 简化的Rust代码格式化
    let mut formatted = String::new();
    let mut indent_level = 0;
    
    for line in code.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            formatted.push('\n');
            continue;
        }
        
        // 处理缩进
        if trimmed.starts_with("fn ") || trimmed.starts_with("struct ") ||
           trimmed.starts_with("enum ") || trimmed.starts_with("impl ") ||
           trimmed.starts_with("trait ") || trimmed.starts_with("mod ") ||
           trimmed.starts_with("if ") || trimmed.starts_with("for ") ||
           trimmed.starts_with("while ") || trimmed.starts_with("loop ") ||
           trimmed.starts_with("match ") || trimmed.starts_with("unsafe ") {
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
            if trimmed.ends_with('{') {
                indent_level += 1;
            }
        } else if trimmed == "}" {
            indent_level = indent_level.saturating_sub(1);
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
        } else {
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
        }
    }
    
    formatted
}

/// 格式化JavaScript代码
fn format_javascript_code(code: &str) -> String {
    // 简化的JavaScript代码格式化
    let mut formatted = String::new();
    let mut indent_level = 0;
    
    for line in code.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            formatted.push('\n');
            continue;
        }
        
        // 处理缩进
        if trimmed.starts_with("function ") || trimmed.starts_with("const ") ||
           trimmed.starts_with("let ") || trimmed.starts_with("var ") ||
           trimmed.starts_with("if ") || trimmed.starts_with("for ") ||
           trimmed.starts_with("while ") || trimmed.starts_with("switch ") ||
           trimmed.starts_with("try ") || trimmed.starts_with("catch ") ||
           trimmed.starts_with("class ") {
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
            if trimmed.ends_with('{') {
                indent_level += 1;
            }
        } else if trimmed == "}" {
            indent_level = indent_level.saturating_sub(1);
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
        } else {
            formatted.push_str(&"    ".repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
        }
    }
    
    formatted
}

/// 语法高亮
pub fn syntax_highlight(code: &str, language: &str) -> String {
    // 这里是一个简化的语法高亮实现
    // 实际应用中可能需要更复杂的语法高亮逻辑
    match language {
        "python" => highlight_python(code),
        "rust" => highlight_rust(code),
        "javascript" => highlight_javascript(code),
        _ => code.to_string(),
    }
}

/// Python语法高亮
fn highlight_python(code: &str) -> String {
    let mut highlighted = String::new();
    
    for line in code.lines() {
        let mut highlighted_line = String::new();
        let words: Vec<&str> = line.split_whitespace().collect();
        
        for (i, word) in words.iter().enumerate() {
            if i > 0 {
                highlighted_line.push(' ');
            }
            
            // 关键字高亮
            if ["def", "class", "if", "else", "elif", "for", "while", "try", "except", 
                 "finally", "with", "as", "import", "from", "return", "break", "continue", 
                 "pass", "True", "False", "None", "and", "or", "not", "in", "is"].contains(word) {
                highlighted_line.push_str(&format!("<span class=\"keyword\">{}</span>", word));
            } else if word.starts_with('#') {
                // 注释高亮
                highlighted_line.push_str(&format!("<span class=\"comment\">{}</span>", word));
            } else if word.starts_with('"') || word.starts_with("'") {
                // 字符串高亮
                highlighted_line.push_str(&format!("<span class=\"string\">{}</span>", word));
            } else if word.parse::<f64>().is_ok() {
                // 数字高亮
                highlighted_line.push_str(&format!("<span class=\"number\">{}</span>", word));
            } else {
                highlighted_line.push_str(word);
            }
        }
        
        highlighted.push_str(&highlighted_line);
        highlighted.push('\n');
    }
    
    highlighted
}

/// Rust语法高亮
fn highlight_rust(code: &str) -> String {
    let mut highlighted = String::new();
    
    for line in code.lines() {
        let mut highlighted_line = String::new();
        let words: Vec<&str> = line.split_whitespace().collect();
        
        for (i, word) in words.iter().enumerate() {
            if i > 0 {
                highlighted_line.push(' ');
            }
            
            // 关键字高亮
            if ["fn", "struct", "enum", "impl", "trait", "mod", "use", "pub", "let", 
                 "mut", "const", "static", "if", "else", "for", "while", "loop", "match", 
                 "return", "break", "continue", "true", "false", "Some", "None", "Ok", 
                 "Err", "Box", "Vec", "String", "i32", "i64", "f32", "f64", "bool"].contains(word) {
                highlighted_line.push_str(&format!("<span class=\"keyword\">{}</span>", word));
            } else if word.starts_with("//") {
                // 注释高亮
                highlighted_line.push_str(&format!("<span class=\"comment\">{}</span>", word));
            } else if word.starts_with('"') {
                // 字符串高亮
                highlighted_line.push_str(&format!("<span class=\"string\">{}</span>", word));
            } else if word.parse::<f64>().is_ok() {
                // 数字高亮
                highlighted_line.push_str(&format!("<span class=\"number\">{}</span>", word));
            } else {
                highlighted_line.push_str(word);
            }
        }
        
        highlighted.push_str(&highlighted_line);
        highlighted.push('\n');
    }
    
    highlighted
}

/// JavaScript语法高亮
fn highlight_javascript(code: &str) -> String {
    let mut highlighted = String::new();
    
    for line in code.lines() {
        let mut highlighted_line = String::new();
        let words: Vec<&str> = line.split_whitespace().collect();
        
        for (i, word) in words.iter().enumerate() {
            if i > 0 {
                highlighted_line.push(' ');
            }
            
            // 关键字高亮
            if ["function", "const", "let", "var", "if", "else", "for", "while", "switch", 
                 "case", "default", "try", "catch", "finally", "throw", "return", "break", 
                 "continue", "class", "extends", "super", "this", "new", "typeof", "instanceof", 
                 "true", "false", "null", "undefined", "NaN", "Infinity"].contains(word) {
                highlighted_line.push_str(&format!("<span class=\"keyword\">{}</span>", word));
            } else if word.starts_with("//") {
                // 注释高亮
                highlighted_line.push_str(&format!("<span class=\"comment\">{}</span>", word));
            } else if word.starts_with('"') || word.starts_with("'") {
                // 字符串高亮
                highlighted_line.push_str(&format!("<span class=\"string\">{}</span>", word));
            } else if word.parse::<f64>().is_ok() {
                // 数字高亮
                highlighted_line.push_str(&format!("<span class=\"number\">{}</span>", word));
            } else {
                highlighted_line.push_str(word);
            }
        }
        
        highlighted.push_str(&highlighted_line);
        highlighted.push('\n');
    }
    
    highlighted
}

/// 代码验证
pub fn validate_code(code: &str, language: &str) -> (bool, Vec<String>) {
    let mut errors = Vec::new();
    let mut is_valid = true;
    
    match language {
        "python" => {
            // 简化的Python代码验证
            if !code.contains("def ") && !code.contains("class ") {
                errors.push("代码应该包含函数或类定义".to_string());
                is_valid = false;
            }
            
            // 检查缩进
            let lines: Vec<&str> = code.lines().collect();
            for (i, line) in lines.iter().enumerate() {
                if line.trim().starts_with("if ") || line.trim().starts_with("for ") ||
                   line.trim().starts_with("while ") || line.trim().starts_with("def ") {
                    if i + 1 < lines.len() && lines[i + 1].trim().is_empty() {
                        errors.push(format!("第{}行后缺少缩进代码块", i + 1));
                        is_valid = false;
                    }
                }
            }
        },
        "rust" => {
            // 简化的Rust代码验证
            if !code.contains("fn ") && !code.contains("struct ") && !code.contains("enum ") {
                errors.push("代码应该包含函数、结构体或枚举定义".to_string());
                is_valid = false;
            }
            
            // 检查大括号匹配
            let open_braces = code.matches('{').count();
            let close_braces = code.matches('}').count();
            if open_braces != close_braces {
                errors.push("大括号不匹配".to_string());
                is_valid = false;
            }
        },
        "javascript" => {
            // 简化的JavaScript代码验证
            if !code.contains("function ") && !code.contains("const ") && 
               !code.contains("let ") && !code.contains("var ") {
                errors.push("代码应该包含函数或变量声明".to_string());
                is_valid = false;
            }
            
            // 检查大括号匹配
            let open_braces = code.matches('{').count();
            let close_braces = code.matches('}').count();
            if open_braces != close_braces {
                errors.push("大括号不匹配".to_string());
                is_valid = false;
            }
        },
        _ => {
            errors.push("不支持的语言类型".to_string());
            is_valid = false;
        }
    }
    
    (is_valid, errors)
} 